package rpc_netty.Encoder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import rpc_1.object.RpcRequest;
import rpc_netty.Client.conf.ConfigureMagment_client;
import rpc_netty.Serializer.HessianSerializer;
import rpc_netty.Serializer.JsonSerializer;
import rpc_netty.Serializer.KryoSerializer;
import rpc_netty.Serializer.PackageType;
import rpc_netty.interfaces.CommonSerializer;
import rpc_netty.server.conf.ConfigureMagment;

/*
自定义协议格式
+---------------+---------------+-----------------+-------------+
|  Magic Number |  Package Type | Serializer Type | Data Length |
|    4 bytes    |    4 bytes    |     4 bytes     |   4 bytes   |
+---------------+---------------+-----------------+-------------+
|                          Data Bytes                           |
|                   Length: ${Data Length}                      |
+---------------------------------------------------------------+

 */
public class CommonEncoder extends MessageToByteEncoder {
    private static final int MAGIC_NUMBER=0xCAFEBABE;
    private static final ConfigureMagment configureMagment=ConfigureMagment.getConfigureMagment();
    private static final ConfigureMagment_client configureMagment_client=ConfigureMagment_client.getConfigureMagment_client();
    private  CommonSerializer serializer;

    public CommonEncoder(int sign){

        String type = sign==0?configureMagment.getProperty("SerializerType"):
                configureMagment_client.getProperty("SerializerType");
        switch (type){
            case "Json":
                serializer =new JsonSerializer();
                break;
            case "Kryo":
                serializer =new KryoSerializer();
                break;
            case "Hessian":
                serializer=new HessianSerializer();
                break;
            default:
                serializer=new JsonSerializer();

        }
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
            out.writeInt(MAGIC_NUMBER);
            if (msg instanceof RpcRequest)
                out.writeInt(PackageType.REQUEST_PACK.getCode());
            else
                out.writeInt(PackageType.RESPONSE_PACK.getCode());
            out.writeInt(serializer.getCode());
            byte[] data = serializer.serialize(msg);
            out.writeInt(data.length);
            out.writeBytes(data);
    }
}
